//
//  LPSanHuiYKSaveRecordViewController.m
//  GongXinDangJian
//
//  Created by 刘应平 on 2017/11/30.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "LPSanHuiYKSaveRecordViewController.h"
#import "LPCostomLabelAndTextFieldAndImageView.h"
#import "MyICRemarkView.h"
#import "ZJSIPotoView.h"
#import "STPhotoBroswer.h"
#import "ZLPhotoActionSheet.h"
#import "LPCostomChooseYearAndMonthAndDayAndHourAndMintueAndMiao.h"
#import <AFNetworking.h>
#import "LPSanHuiYKSaveRecordModel.h"

@interface LPSanHuiYKSaveRecordViewController ()<ZJSIPotoViewDelegate,LPCostomLabelAndTextFieldAndImageViewDelegate,LPCostomChooseYearAndMonthAndDayAndHourAndMintueAndMiaoDelegate>{
    NSInteger _index;/**< 标记图片数组的长度 */
    NSInteger _deleImageIndex;/**< 删除图片的下标 */
}
/**    */
@property (strong, nonatomic) UIScrollView  *backScrollView;
/**  会议名称  */
@property (strong, nonatomic) LPCostomLabelAndTextFieldAndImageView  *meetNameView;
/**  时间  */
@property (strong, nonatomic) LPCostomLabelAndTextFieldAndImageView  *timeView;
/**  时间选择  */
@property (strong, nonatomic) LPCostomChooseYearAndMonthAndDayAndHourAndMintueAndMiao  *pickTime;

/**  类型  */
@property (strong, nonatomic) LPCostomLabelAndTextFieldAndImageView  *typeView;
/**  会议内容  */
@property (strong, nonatomic) MyICRemarkView  *remarkView;
/**  图片  */
@property (strong, nonatomic) ZJSIPotoView  *potoView;
/** 图片数组 */
@property (nonatomic, strong) NSMutableArray *imageArray;
/**  保存按钮  */
@property (strong, nonatomic) UIButton  *saveButton;
/**  当前时间  */
@property (strong, nonatomic) NSString  *currentString;
/**  请求参数  */
@property (strong, nonatomic) NSString  *postUrl;


@end

@implementation LPSanHuiYKSaveRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentString = [NSDateFormatter stringTimeYearMonthDayHourMintueWithDate:[NSDate date]];
    self.titlelabel.text = @"三会一课";
    [self layoutUI];
    if (self.model.ID) {
        [self.saveButton setTitle:@"修改" forState:UIControlStateNormal];
        self.postUrl = @"miit.action.ShykAction[updateShyk]";
        __weak typeof(self) weakSelf = self;
        [LPRequestManager request_miitactionShykActiongetShykResWithMSG_ID:self.model.ID TYPE_VALUE:self.model.TYPE_VALUE successBlock:^(id object) {
            NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
            if ([model.STATE integerValue] == 20000) {
                NSArray *array = [object objectForKey:@"SHYKS"];
                self.model = [LPSanHuiMeetingListModel yy_modelWithJSON:array[0]];
                self.meetNameView.secondTextField.text = self.model.NAME;
                self.timeView.secondTextField.text = self.model.PUBLISH_DATE;
                self.remarkView.textView.text = self.model.CONTENT;
                NSArray *imageArray = [object objectForKey:@"MSG_RES"];
                for (int i = 0; i < imageArray.count; i ++) {
                    NSDictionary *dic = imageArray[i];
                    UIImageView * aa = [[UIImageView alloc]init];
                    [self.view addSubview:aa];
                    [aa sd_setImageWithURL:CREATEURL(dic[@"RES_URL"]) completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                        NSData *data = [ToolClass compressionImageWithImage:image compressionMaxLimit:COMPRESSIONMAXLIMIT];
                        NetWorkUploadFileModel *model = [NetWorkUploadFileModel new];
                        model.FILE_NAME = [NSDateFormatter stringTimeWithDate:[NSDate date]];
                        model.FILE_INDEX = [NSString stringWithFormat:@"%d",i];
                        model.FILE_PATH = data;
                        model.NAME = @"SHYK_IMG";
                        [weakSelf.imageArray addObject:model];
                        if (weakSelf.imageArray.count == imageArray.count) {
                            _index = self.imageArray.count;
                            [weakSelf.potoView updateUI_PotoArray:weakSelf.imageArray];
                            weakSelf.potoView.sd_layout
                            .topSpaceToView(weakSelf.remarkView, 0)
                            .leftSpaceToView(weakSelf.backScrollView, 0)
                            .rightSpaceToView(weakSelf.backScrollView, 0)
                            .heightIs(weakSelf.potoView.height);
                        }
                        [aa removeFromSuperview];
                    }];
                    
                }
            
                
                
            }
        } failBlock:^(id object) {
            
        }];
       
    }else{
        [self.saveButton setTitle:@"保存" forState:UIControlStateNormal];
        self.postUrl = @"miit.action.ShykAction[addShyk]";
    }
}




#pragma mark - 界面
- (void)layoutUI{
    [self.view addSubview:self.backScrollView];
    [self.view addSubview:self.saveButton];
    [self.backScrollView addSubview:self.meetNameView];
    [self.backScrollView addSubview:self.timeView];
    [self.backScrollView addSubview:self.typeView];
    [self.backScrollView addSubview:self.remarkView];
    [self.backScrollView addSubview:self.potoView];
    
    self.saveButton.sd_layout
    .bottomSpaceToView(self.view, 10 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.view, 30 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.view, 30 * [UIScreen zj_screenWScale])
    .heightIs(45 * [UIScreen zj_screenHScale]);
    
    
    self.meetNameView.sd_layout
    .leftEqualToView(self.backScrollView)
    .topSpaceToView(self.backScrollView, 20 * [UIScreen zj_screenHScale])
    .widthIs(self.meetNameView.width)
    .heightIs(self.meetNameView.height);
    
    self.timeView.sd_layout
    .leftEqualToView(self.backScrollView)
    .topSpaceToView(self.meetNameView, 10 * [UIScreen zj_screenHScale])
    .widthIs(self.timeView.width)
    .heightIs(self.timeView.height);
    
    self.typeView.sd_layout
    .leftEqualToView(self.backScrollView)
    .topSpaceToView(self.timeView, 10 * [UIScreen zj_screenHScale])
    .widthIs(self.timeView.width)
    .heightIs(self.timeView.height);
    
    self.remarkView.sd_layout
    .leftEqualToView(self.backScrollView)
    .topSpaceToView(self.typeView, 10 * [UIScreen zj_screenHScale])
    .widthIs(self.remarkView.width)
    .heightIs(self.remarkView.height);
    
    self.potoView.sd_layout
    .leftEqualToView(self.backScrollView)
    .topSpaceToView(self.remarkView, 0 * [UIScreen zj_screenHScale])
    .widthIs(self.potoView.width)
    .heightIs(self.potoView.height);
    
    [self.backScrollView setupAutoContentSizeWithBottomView:self.potoView bottomMargin:30 * [UIScreen zj_screenHScale]];
    
}


#pragma mark - 保存
- (void)clickButton{
    if (self.meetNameView.secondTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请输入会议名称" inview:[UIApplication sharedApplication].keyWindow];
         [self.meetNameView.secondTextField becomeFirstResponder];
        return;
    }
    
    if (self.timeView.secondTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请选择会议时间" inview:[UIApplication sharedApplication].keyWindow];
        return;
    }
    
    if (self.remarkView.textView.text.length == 0) {
        [YJProgressHUD showSuccess:@"请输入会议内容" inview:self.view];
        [self.remarkView.textView becomeFirstResponder];
        return;
    }
    
    
    LPSanHuiYKSaveRecordModel *paramer = [LPSanHuiYKSaveRecordModel new];
    if (self.model.ID) {
            paramer.ID = self.model.ID;
    }

    paramer.CREATE_ID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID;
    paramer.TYPE_TEXT = self.headline;
    paramer.TYPE_VALUE = self.type;
    paramer.PUBLISH_DATE = self.timeView.secondTextField.text;
    paramer.NAME = self.meetNameView.secondTextField.text;
    paramer.CONTENT = self.remarkView.textView.text;
    paramer.UPLOAD_FILES = self.imageArray;
    [self netWorking:paramer];
    
}

- (void)netWorking:(LPSanHuiYKSaveRecordModel *)parameter1{
    if (self.model.ID) {
        [YJProgressHUD showMessage:@"修改中..." duration:10 view:self.view];
    }else{
        [YJProgressHUD showMessage:@"记录中..." duration:10 view:self.view];
    }
    __weak typeof(self) weakSelf = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",@"text/plain", nil];
    
    //1、把文件对象数组转化成数组
    NSArray *fileArray = [parameter1.UPLOAD_FILES yy_modelToJSONObject];
    //2、除去data，得到数组
    __block NSMutableArray *nofileDataArray = [NSMutableArray array];//保存新数组
    
    NSDictionary *netWorkUpLoadModel = [parameter1 yy_modelToJSONObject];
    
    [fileArray enumerateObjectsUsingBlock:^(NSMutableDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeObjectForKey:@"fileUrl"];
        [nofileDataArray addObject:obj];
    }];
    
    
    NSString * dateString = [NSString stringWithFormat:@"FILES_%@_KEYS",[NSString getCurrentDate]];
    
    [manager POST:UPLOADURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [netWorkUpLoadModel.allKeys enumerateObjectsUsingBlock:^(NSString *  _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
            //不为fileArray 且有值时
            if (![key isEqualToString:@"UPLOAD_FILES"] && [netWorkUpLoadModel objectForKey:key] && ![key isEqualToString:@"frequency"]) {
                [formData appendPartWithFormData:[netWorkUpLoadModel[key] dataUsingEncoding:NSUTF8StringEncoding] name:key];
            }
        }];
        
        [parameter1.UPLOAD_FILES enumerateObjectsUsingBlock:^(NetWorkUploadFileModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.FILE_PATH) {
                NSData  *fileData= obj.FILE_PATH;//二进制数据
                NSString *mimeType= @"image/jpeg";//文件类型
                
                //拼接最新的文件名
                NSString *fileName = [NSString stringWithFormat:@"%ld%@",(unsigned long)idx,@".jpg"];
                [formData appendPartWithFileData:fileData name: obj.NAME fileName:fileName mimeType:mimeType];
            }
        }];
        
        [formData appendPartWithFormData:[nofileDataArray yy_modelToJSONData] name:dateString];
        [formData appendPartWithFormData:[self.postUrl dataUsingEncoding:NSUTF8StringEncoding] name:@"ACTION_XML"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [YJProgressHUD hide];
        //成功
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:responseObject];
        if ([model.STATE isEqualToString:@"20000"]) {
            
            if (self.block) {
                self.block();
            }
            if (self.model.ID) {
                 [YJProgressHUD showSuccess:@"修改成功" inview:weakSelf.view];
            }else{
                 [YJProgressHUD showSuccess:@"记录成功" inview:weakSelf.view];
            }
           
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            if (self.model.ID) {
                [YJProgressHUD showSuccess:@"修改失败" inview:weakSelf.view];
            }else{
                [YJProgressHUD showSuccess:@"记录失败" inview:weakSelf.view];
            }
            
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [YJProgressHUD hide];
        //失败
        if (self.model.ID) {
            [YJProgressHUD showSuccess:@"修改失败" inview:weakSelf.view];
        }else{
            [YJProgressHUD showSuccess:@"记录失败" inview:weakSelf.view];
        }
        
        
    }];
    
}



#pragma mark - LPCostomLabelAndTextFieldAndImageViewDelegate
- (void)LPCostomLabelAndTextFieldAndImageWith:(LPCostomLabelAndTextFieldAndImageView *)view click:(BOOL)click{
    [self.pickTime show:self.timeView.secondTextField.text];
}

#pragma mark - LPChooseYearAndMonthAndDayAndHourAndMinuteDelegate
- (void)LPCostomChooseYearAndMonthAndDayAndHourAndMintueAndMiaoWithTitle:(NSString *)string{
    self.timeView.secondTextField.text = string;
}

#pragma mark - ZJSIPotoViewDelegate(图片模块) 协议方法
- (void)ZJSIPotoViewDelegate_addPotoClick{
    [self.view endEditing:YES];
    if (self.imageArray.count == 9) {
        [YJProgressHUD showMessage:@"最多选择9张图片" inView:self.view];
    }
    else{
        _index = self.imageArray.count;
        //图片多选模块
        ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
        //设置最大选择数量
        actionSheet.maxSelectCount = 9 - self.imageArray.count;
        //设置预览图最大数目
        actionSheet.maxPreviewCount = 20;
        __weak typeof(self) weakSelf = self;
        [actionSheet showWithSender:self animate:YES lastSelectPhotoModels:nil completion:^(NSArray<UIImage *> * _Nonnull selectPhotos, NSArray<ZLSelectPhotoModel *> * _Nonnull selectPhotoModels) {
            
            [selectPhotos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSData * data = [ToolClass compressionImageWithImage:obj compressionMaxLimit:COMPRESSIONMAXLIMIT];
                NetWorkUploadFileModel *model = [NetWorkUploadFileModel new];
                model.FILE_NAME = [NSDateFormatter stringTimeWithDate:[NSDate date]];
                model.FILE_INDEX = [NSString stringWithFormat:@"%ld",idx];
                model.FILE_PATH = data;
                model.NAME = @"SHYK_IMG";
                [weakSelf.imageArray addObject:model];
            }];
            _index = self.imageArray.count;
            [weakSelf.potoView updateUI_PotoArray:weakSelf.imageArray];
            weakSelf.potoView.sd_layout
            .topSpaceToView(self.remarkView, 0)
            .leftSpaceToView(self.backScrollView, 0)
            .rightSpaceToView(self.backScrollView, 0)
            .heightIs(self.potoView.height);
            
        }];
    }
    
    
}
- (void)ZJSIPotoViewDelegate_deletePotoClick_index:(NSInteger)index{
    _deleImageIndex = index;
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否确定删除图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.imageArray removeObjectAtIndex:_deleImageIndex];
        _index = self.imageArray.count;
        [self.potoView updateUI_PotoArray:self.imageArray];
        self.potoView.sd_layout
        .topSpaceToView(self.remarkView, 0)
        .leftEqualToView(self.backScrollView)
        .rightEqualToView(self.backScrollView)
        .heightIs(self.potoView.height);
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
    
    
}
- (void)ZJSIPotoViewDelegate_potoImageClick_index:(NSInteger)index{
    __block NSMutableArray *imageDataArray = [NSMutableArray array];
    [self.imageArray enumerateObjectsUsingBlock:^(NetWorkUploadFileModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *dict = @{@"image":[UIImage imageWithData:obj.FILE_PATH]};
        [imageDataArray addObject:dict];
    }];
    STPhotoBroswer *view = [[STPhotoBroswer alloc]initWithFrame:CGRectMake(0, 0,self.view.width , self.view.height) ImageArray:imageDataArray currentIndex:index];
    [view show];
}


#pragma mark - getter

- (LPCostomLabelAndTextFieldAndImageView *)meetNameView{
    if (!_meetNameView) {
        _meetNameView = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0,0, self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"会议名称 :" placehold:@"" imageString:@""];
        _meetNameView.secondTextField.userInteractionEnabled = YES;
        _meetNameView.maxNumber = 50;
        _meetNameView.isShow = YES;
    }
    return _meetNameView;
}


- (LPCostomLabelAndTextFieldAndImageView *)timeView{
    if (!_timeView) {
        _timeView = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0,0, self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"时间 :" placehold:@"" imageString:@"calendar"];
        _timeView.delegate = self;
        _timeView.isShow = YES;
    }
    return _timeView;
}

- (LPCostomLabelAndTextFieldAndImageView *)typeView{
    if (!_typeView) {
        _typeView = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0,0, self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"类型 :" placehold:@"" imageString:@""];
        _typeView.secondTextField.text = self.headline;
        _typeView.isShow = YES;
    }
    return _typeView;
}

- (MyICRemarkView *)remarkView{
    if (_remarkView == nil){
        _remarkView = [[MyICRemarkView alloc] initWithFrame:CGRectMake(0,0, self.view.width, 195 * [UIScreen zj_screenHScale]) title:@"内容 :"];
        _remarkView.textView.xx_placeholder = @"不得记录任何涉密内容";
        _remarkView.maxNumber = 200;
    }
    return _remarkView;
}


- (ZJSIPotoView *)potoView{
    if (_potoView == nil){
        _potoView = [[ZJSIPotoView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 195  * [UIScreen zj_screenHScale]) title:@"上传照片（ 不得上传任何涉密图片 ）"];
        [_potoView updateUI_PotoArray:nil];
        _potoView.deletate = self;
    }
    return _potoView;
}

- (UIButton *)saveButton{
    if (!_saveButton) {
        _saveButton = ({
            UIButton *button = [UIButton new];
            
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.titleLabel.font = LYPFONT(17);
            button.backgroundColor = [UIColor themeColor];
            [button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
            button.layer.cornerRadius = 4;
            button.layer.masksToBounds = YES;
            button;
            
        });
    }
    return _saveButton;
}

- (UIScrollView *)backScrollView{
    if (_backScrollView == nil) {
        _backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, navHeight, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] - navHeight - 70 * [UIScreen zj_screenHScale])];
        _backScrollView.showsHorizontalScrollIndicator = NO;
    }
    return _backScrollView;
}


- (NSMutableArray *)imageArray{
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (LPCostomChooseYearAndMonthAndDayAndHourAndMintueAndMiao *)pickTime{
    if (_pickTime == nil) {
        _pickTime = [[LPCostomChooseYearAndMonthAndDayAndHourAndMintueAndMiao alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
        _pickTime.delegate = self;
    }
    return _pickTime;
}
@end
